package com.fxu.role.task;

import cn.hutool.core.util.ReflectUtil;
import com.fxu.framework.core.service.impl.ApiServiceImpl;
import com.fxu.framework.core.util.BeanUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 日志收集到数据库
 * @author fangxu
 * @since 2022-03-11
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LogTrackTask {
    private final ApiServiceImpl apiService;
    private final RedisTemplate<String, Object> redisTemplate;

    // 每隔一段时间保存缓存日志数据到数据库 = 10分钟
//    @Scheduled(fixedDelay = 10 * 60 * 1000)
//    public synchronized void logSave() {
//        Long time = System.currentTimeMillis();
//        Long size = redisTemplate.opsForList().size(LogTrackAspect.REDIS_KEY);
//        log.info("LogTrackTask 开始! list.size()={}", size);
//        if (size != null && size > 0) {
//            List<Object> list = redisTemplate.opsForList().leftPop(LogTrackAspect.REDIS_KEY, size);
//
//            if (list != null && list.size() > 0) {
//                List<LogTrack> logTrackList = new ArrayList<>();
//                for (Object obj : list) {
//                    LogTrack logTrack = BeanUtil.copyProperties(obj, LogTrack.class);
//                    Object objVal = ReflectUtil.getFieldValue(obj, "value");
//                    logTrack.setMark(objVal == null ? "" : objVal.toString());
//                    objVal = ReflectUtil.getFieldValue(obj, "exception");
//                    logTrack.setException(objVal == null ? "" : objVal.toString());
//                    logTrackList.add(logTrack);
//                }
//                apiService.saveBatchIgnore(logTrackList);
//            }
//        }
//        log.info("LogTrackTask 结束! 耗时={}ms", (System.currentTimeMillis() - time));
//    }
}